package com.lvy.hczn.transmit.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lvy.hczn.front.common.constant.Constants;
import com.lvy.hczn.front.common.constant.MqConstants;
import com.lvy.hczn.front.common.core.domain.BaseModel;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.system.domain.business.*;
import com.lvy.hczn.front.system.service.IProductionProcessingTypeService;
import com.lvy.hczn.front.system.service.WarehouseService;
import com.lvy.hczn.mq.rocket.ParamInfo;
import com.lvy.hczn.mq.rocket.ProducerUtil;
import com.lvy.hczn.transmit.common.ConstantTransmit;
import com.lvy.hczn.transmit.domain.dto.cteck.DeliveryOrderInfo;
import com.lvy.hczn.transmit.domain.dto.cteck.DeliveryOrderInfoDetail;
import com.lvy.hczn.transmit.service.GoodsBoxService;
import com.lvy.hczn.transmit.service.TAccessManagerService;
import com.lvy.hczn.transmit.service.TDeliveryOrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class TDeliveryOrderInfoServiceImpl implements TDeliveryOrderInfoService {

    @Autowired
    private ProducerUtil producerUtil;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private TAccessManagerService tAccessManagerService;

    @Autowired
    private GoodsBoxService goodsBoxService;

    @Autowired
    private IProductionProcessingTypeService productionProcessingTypeService;

    /**
     * 从平台同步配送单
     *
     * @param request
     * @param info
     * @return void
     * @author yw
     * @date 2023-06-03 11:26:41
     */
    @Override
    public void syncDeliveryFromPlatform(HttpServletRequest request, ParamInfo info) {
        log.error("syncDeliveryFromPlatform:{}", JSON.toJSONString(info));
        DeliveryOrderInfo deliveryOrderInfo = JSON.parseObject(JSON.toJSONString(info.getData()), DeliveryOrderInfo.class);
        if (deliveryOrderInfo == null) {
            throw new UtilException("数据为空");
        }
        if (StrUtil.hasEmpty(deliveryOrderInfo.getDeliveryCode(), deliveryOrderInfo.getServiceCode())) {
            throw new UtilException("配送单号或");
        }
        if (deliveryOrderInfo.getDeliveryType() == null) {
            throw new UtilException("配送商类型为空");
        }
        if (deliveryOrderInfo.getServiceType() == null) {
            throw new UtilException("业务类型为空");
        }
        if (StrUtil.isEmpty(deliveryOrderInfo.getPickupAddress())) {
            throw new UtilException("取件地址为空");
        }
        if (StrUtil.isEmpty(deliveryOrderInfo.getDestinyAddress())) {
            throw new UtilException("目的地址为空");
        }
        if (deliveryOrderInfo.getStatus() == null) {
            throw new UtilException("状态为空");
        }
        if (deliveryOrderInfo.getServiceType() == ConstantTransmit.DELIVERY_SERVICE_TYPE_ONE) {
            //1销售配送
            initWarehouseSaleOrder(deliveryOrderInfo, deliveryOrderInfo.getPickup(), "0");
            access(deliveryOrderInfo.getEntryCode(), deliveryOrderInfo.getDeliveryCode(), Constants.ACCESS_TYPE_SEVEN, deliveryOrderInfo.getPickup());
        } else if (deliveryOrderInfo.getServiceType() == ConstantTransmit.DELIVERY_SERVICE_TYPE_TWO) {
            //2销售退货配送
            //仓库编号取：deliveryOrderInfo.getDestiny()
//            deliveryOrderInfo.setReturnOfGoods(true);
            initWarehouseSaleOrder(deliveryOrderInfo, deliveryOrderInfo.getDestiny(), "3");
            access(deliveryOrderInfo.getEntryCode(), deliveryOrderInfo.getDeliveryCode(), Constants.ACCESS_TYPE_FIVE, deliveryOrderInfo.getDestiny());
        } else if (deliveryOrderInfo.getServiceType() == ConstantTransmit.DELIVERY_SERVICE_TYPE_THREE) {
            //发货配送
            initWarehousePurchaseOrder(deliveryOrderInfo);
            access(deliveryOrderInfo.getEntryCode(), deliveryOrderInfo.getDeliveryCode(), Constants.ACCESS_TYPE_TWO, deliveryOrderInfo.getDestiny());
        } else if (deliveryOrderInfo.getServiceType() == ConstantTransmit.DELIVERY_SERVICE_TYPE_FOUR) {
            //4拒收配送
//            deliveryOrderInfo.setGoodsRejected(true);
            initWarehouseSaleOrder(deliveryOrderInfo, deliveryOrderInfo.getDestiny(), "3");
            access(deliveryOrderInfo.getEntryCode(), deliveryOrderInfo.getDeliveryCode(), Constants.ACCESS_TYPE_FIVE, deliveryOrderInfo.getDestiny());
        }
    }

    /**
     * 门禁
     *
     * @param entryCode
     * @return void
     * @author yw
     * @date 2023-06-04 17:09:22
     */
    @Override
    public void access(String entryCode, String deliveryCode, Integer type, String warehouseCode) {
        AccessManager accessManager = new AccessManager();
        ParamInfo<AccessManager> paramInfo = new ParamInfo<>();
        paramInfo.setWarehouseCode(warehouseCode);

        accessManager.setSourceCode(deliveryCode);
        if (StrUtil.isEmpty(entryCode)) {
            accessManager.setAccessCode(deliveryCode);
        } else {
            accessManager.setAccessCode(entryCode);
        }
        accessManager.setType(type);
        paramInfo.setData(accessManager);
        tAccessManagerService.syncBoxLeasePlatform(paramInfo);
    }

    /**
     * 仓库销售订单及明细数据转化
     *
     * @param deliveryOrderInfo
     * @return void
     * @author yw
     * @date 2023-06-04 15:52:46
     */
    public void initWarehouseSaleOrder(DeliveryOrderInfo deliveryOrderInfo, String warehouseCode, String status) {

        Warehouse warehouse = warehouseService.getOne(Wrappers.<Warehouse>lambdaQuery().eq(Warehouse::getWarehouseCode, warehouseCode).last("limit 1"));
        if (warehouse == null) {
            throw new UtilException("仓库编码不存在，请检查仓库编号：" + warehouseCode);
        }
        SaleOrder saleOrder = new SaleOrder();
        ParamInfo<SaleOrder> info = new ParamInfo<>();
        if (!StrUtil.isEmpty(deliveryOrderInfo.getOtherNo())) {
            saleOrder.setSaleOrderCode(deliveryOrderInfo.getOtherNo());
        } else {
            saleOrder.setSaleOrderCode(deliveryOrderInfo.getDeliveryCode());
        }

        saleOrder.setMemberCode(deliveryOrderInfo.getBuyerId());
        saleOrder.setDeliveryCode(deliveryOrderInfo.getDeliveryCode());
        saleOrder.setName(deliveryOrderInfo.getDestinyPerson());
//        saleOrder.setPhone(deliveryOrderInfo.getDestinyPhone());
//        saleOrder.setAddress(deliveryOrderInfo.getDestinyAddress());
        saleOrder.setWarehouseCode(warehouseCode);
        saleOrder.setRemark(deliveryOrderInfo.getRemark());
        saleOrder.setServiceCode(deliveryOrderInfo.getServiceCode());
        saleOrder.setReturnOfGoods(deliveryOrderInfo.isReturnOfGoods());
        saleOrder.setGoodsRejected(deliveryOrderInfo.isGoodsRejected());
        saleOrder.setType(String.valueOf(deliveryOrderInfo.getServiceType()));
        saleOrder.setPhone(deliveryOrderInfo.getDestinyPhone());
        if (deliveryOrderInfo.getLatestArriveTime() != null) {
            saleOrder.setDeliveryTime(LocalDateTimeUtil.of(deliveryOrderInfo.getLatestArriveTime()));
        } else {
            /*没有预约收获时间，当前买则默认下个小时送达，**/
            LocalDateTime time = LocalDateTime.now();
            time = time.plusHours(1);
            saleOrder.setDeliveryTime(time);
        }
        saleOrder.setSourceOrigin(deliveryOrderInfo.getSourceOrigin());
        saleOrder.setStatus(status);
        if (StrUtil.isEmpty(deliveryOrderInfo.getSourceId())) {
            saleOrder.setSourceId(deliveryOrderInfo.getId() + Constants.SOURCE_ID_DEFAULT + deliveryOrderInfo.getDeliveryCode());
        } else {
            saleOrder.setSourceId(deliveryOrderInfo.getId() + deliveryOrderInfo.getSourceId() + deliveryOrderInfo.getDeliveryCode());
        }
        saleOrder.setDeliveryClerk(deliveryOrderInfo.getDeliveryUserId());
        saleOrder.setDeliveryArea(deliveryOrderInfo.getSortCode());
        if (deliveryOrderInfo.getList() != null) {
            List<SaleOrderDetail> list = new ArrayList<>();
            deliveryOrderInfo.getList().forEach(item -> {
                SaleOrderDetail saleOrderDetail = new SaleOrderDetail();
                saleOrderDetail.setSaleOrderCode(saleOrder.getSaleOrderCode());
                saleOrderDetail.setSourceId(saleOrder.getSourceId() + item.getId());
                saleOrderDetail.setGoodsCode(item.getMerchandiseName());
                saleOrderDetail.setSkuCode(item.getMerchandiseSku());
                saleOrderDetail.setSupplierCode(item.getSupplierCode());
                saleOrderDetail.setSupplierName(item.getSupplierName());
                saleOrderDetail.setDataType(item.getDataType());
                saleOrderDetail.setMaterialProcessId(item.getProcessingId());
                if (item.getOutStock() == null) {
                    saleOrderDetail.setOutStock(com.lvy.hczn.front.common.constant.Constants.OUT_STOCK_ZERO);
                } else {
                    saleOrderDetail.setOutStock(item.getOutStock());
                }

                if (StrUtil.isEmpty(item.getMerchandiseSpecif())) {
                    saleOrderDetail.setSpecCode(item.getMerchandiseSku());
                } else {
                    saleOrderDetail.setSpecCode(item.getMerchandiseSpecif());
                }

                saleOrderDetail.setSpuId(item.getMerchandiseCode());
                saleOrderDetail.setQuantity(item.getMerchandiseNum());
                saleOrderDetail.setUnit(item.getUnit());
                if (status.equals("3")) {
                    //总重量
                    saleOrderDetail.setWeight(new BigDecimal(item.getMerchandiseNum()).multiply(item.getMerchandiseWeight()).setScale(2, RoundingMode.HALF_UP));
                } else if (status.equals("0")) {
                    //销售单区分C端和B端
                    changeDataBySourceOrigin(deliveryOrderInfo.getSourceOrigin(), item, saleOrderDetail);
                } else {
                    saleOrderDetail.setWeight(item.getMerchandiseWeight());
                }

                saleOrderDetail.setBatchCode(saleOrder.getSaleOrderCode());
                saleOrderDetail.setVolume(item.getMerchandiseVolume());
                saleOrderDetail.setTakeDeliveryOf(0);
                saleOrderDetail.setStatus(status);
                list.add(saleOrderDetail);
            });
            saleOrder.setList(list);
        }
        info.setData(saleOrder);
        String topic = warehouseService.selectRegionAreaTopic(warehouse);
        String tag = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_WAREHOUSE_DELIVERY_SALE;
        try {
            producerUtil.sendAsyncMsg(topic, tag, JSON.toJSONString(info).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
        } catch (Exception e) {
            throw new UtilException("数据发送异常");
        }
    }

    /**
     * 根据中台传入的数据，校验B端还是C端，然后初步同步端的数量和重量
     *
     * @param sourceOrigin
     * @param item
     * @param saleOrderDetail
     */
    public void changeDataBySourceOrigin(Integer sourceOrigin, DeliveryOrderInfoDetail item, SaleOrderDetail saleOrderDetail) {

        if (Objects.equals(sourceOrigin, Constants.SOURCE_ORIGIN_B) && !StrUtil.isEmpty(item.getProcessingId())) {
            /*批发逻辑**/
            ProductionProcessingType productionProcessingType = productionProcessingTypeService.getOne(Wrappers.<ProductionProcessingType>lambdaQuery().eq(BaseModel::getId, item.getProcessingId()));
            if (productionProcessingType == null) {
                throw new UtilException("加工方式id为" + item.getProcessingId() + "的加工方式不存在");
            }
                BigDecimal totalWeight = item.getMerchandiseWeight();
            if (productionProcessingType.getPriceUnit().equals("0")) {
                //按重量处理分拣，如：买10斤，每斤打包成一份，把单据数量和重量设置成，数量10份，每份重量1斤
                saleOrderDetail.setWeight(productionProcessingType.getPriceNum());
                int totalQuantity = totalWeight.divide(productionProcessingType.getPriceNum(), 0, RoundingMode.HALF_UP).intValue();
                saleOrderDetail.setQuantity(totalQuantity);
            } else if (productionProcessingType.getPriceUnit().equals("1")) {
                //按数量处理分拣，如：买10瓶，每两瓶打包成一份，把单据数量和重量设置成，数量5份，每份重量2斤
                BigDecimal quantity = new BigDecimal(item.getMerchandiseNum());
                int actQuantity = quantity.divide(productionProcessingType.getPriceNum(), 0, RoundingMode.DOWN).intValue();
                BigDecimal actWeight = item.getMerchandiseWeight().divide(new BigDecimal(actQuantity), 0, RoundingMode.HALF_UP);
                saleOrderDetail.setWeight(actWeight);
                saleOrderDetail.setQuantity(actQuantity);
            }
        } else {
            /*商城C端用户销售逻辑**/
            saleOrderDetail.setWeight(item.getMerchandiseWeight());
        }
    }

    /**
     * 转化数据，初始化仓库角度的采购单（仓库项目先出，跟现有单据不太一致，懒得改）
     *
     * @param deliveryOrderInfo
     * @return void
     * @author yw
     * @date 2023-06-04 14:55:57
     */
    public void initWarehousePurchaseOrder(DeliveryOrderInfo deliveryOrderInfo) {
        Warehouse warehouse = warehouseService.getOne(Wrappers.<Warehouse>lambdaQuery().eq(Warehouse::getWarehouseCode, deliveryOrderInfo.getDestiny()).last("limit 1"));
        if (warehouse == null) {
            throw new UtilException("仓库编码不存在，请检查仓库编码：" + deliveryOrderInfo.getDestiny());
        }
        PurchaseOrder purchaseOrder = new PurchaseOrder();
        List<PurchaseOrderDetail> list = new ArrayList<>();
        List<GoodsBox> boxCodeList = new ArrayList<>();
        //3发货配送
        purchaseOrder.setWarehouseCode(deliveryOrderInfo.getDestiny());
        purchaseOrder.setSupplierCode(deliveryOrderInfo.getPickup());
        purchaseOrder.setDeliveryCode(deliveryOrderInfo.getDeliveryCode());
        purchaseOrder.setPurchaseOrderCode(deliveryOrderInfo.getDeliveryCode());
        purchaseOrder.setServiceCode(deliveryOrderInfo.getServiceCode());
        purchaseOrder.setServiceType(deliveryOrderInfo.getServiceType());
        if (StrUtil.isEmpty(deliveryOrderInfo.getSourceId())) {
            purchaseOrder.setSourceId(deliveryOrderInfo.getId() + Constants.SOURCE_ID_DEFAULT + purchaseOrder.getPurchaseOrderCode());
        } else {
            purchaseOrder.setSourceId(deliveryOrderInfo.getId() + deliveryOrderInfo.getSourceId());
        }

        purchaseOrder.setDeliveryWay("2");
        if (deliveryOrderInfo.getDeliveryType() != null) {
            purchaseOrder.setDeliveryType(deliveryOrderInfo.getDeliveryType());
        } else {
            purchaseOrder.setDeliveryType(2);
        }
        purchaseOrder.setPurchaseSource("0");
        purchaseOrder.setConfirmStatus("1");
        purchaseOrder.setDeliveryTime(LocalDateTimeUtil.of(deliveryOrderInfo.getPickupTime()));
        purchaseOrder.setDeliveryStatus("0");
        purchaseOrder.setDistributionCost(deliveryOrderInfo.getDeliveryFee());
        purchaseOrder.setPrice(BigDecimal.ZERO);
        purchaseOrder.setCreateBy(deliveryOrderInfo.getCreateBy());
        purchaseOrder.setRemark(deliveryOrderInfo.getRemark());
        purchaseOrder.setPurchaseType(Constants.PURCHASE_TYPE_ZERO);
        purchaseOrder.setSourceOrigin(deliveryOrderInfo.getSourceOrigin());
        if (deliveryOrderInfo.getList() != null) {
            for (DeliveryOrderInfoDetail item : deliveryOrderInfo.getList()) {
                if (StrUtil.isEmpty(item.getContainerId())) {
                    throw new UtilException("编号为" + item.getCartonCode() + "的货箱类型id为空");
                }
                /*if (StrUtil.isEmpty(item.getProducerId())) {
                    throw new UtilException("编号为" + item.getCartonCode() + "的货箱生产商为空");
                }*/
                PurchaseOrderDetail purchaseOrderDetail = new PurchaseOrderDetail();
                purchaseOrderDetail.setSpuId(item.getMerchandiseCode());
                purchaseOrderDetail.setPurchaseOrderCode(purchaseOrder.getPurchaseOrderCode());
                purchaseOrderDetail.setBoxCode(item.getCartonCode());
                purchaseOrderDetail.setBatchCode(purchaseOrder.getPurchaseOrderCode());
                purchaseOrderDetail.setSourceId(purchaseOrder.getSourceId() + item.getId());

                if (item.getOutStock() == null) {
                    purchaseOrderDetail.setOutStock(com.lvy.hczn.front.common.constant.Constants.OUT_STOCK_ZERO);
                } else {
                    purchaseOrderDetail.setOutStock(item.getOutStock());
                }

                //purchaseOrderDetail.setSpecCode(item.getMerchandiseSpecif());
                //平台现在的sku=spec,MerchandiseSpecif可能是中文
                if (StrUtil.isEmpty(item.getMerchandiseSpecif())) {
                    purchaseOrderDetail.setSpecCode(item.getMerchandiseSku());
                } else {
                    purchaseOrderDetail.setSpecCode(item.getMerchandiseSpecif());
                }

//                purchaseOrderDetail.setBoxCode(item.getCartonCode());
                purchaseOrderDetail.setPrice(BigDecimal.ZERO);
                purchaseOrderDetail.setSkuCode(item.getMerchandiseSku());
                purchaseOrderDetail.setWeight(item.getMerchandiseWeight());
                purchaseOrderDetail.setPurchaseWeight(item.getMerchandiseWeight());
                purchaseOrderDetail.setQuantity(item.getMerchandiseNum());
                purchaseOrderDetail.setPurchaseQuantity(item.getMerchandiseNum());
                purchaseOrderDetail.setUnit(item.getUnit());
                purchaseOrderDetail.setSupplierCode(item.getSupplierCode());
                purchaseOrderDetail.setStatus("0");
                purchaseOrderDetail.setVolume(item.getMerchandiseVolume().multiply(new BigDecimal(item.getMerchandiseNum())));
                purchaseOrderDetail.setProduceDate(LocalDateTimeUtil.of(item.getProducerDate()));
                purchaseOrderDetail.setWarrantyDate(item.getWarrantyDate());
                purchaseOrderDetail.setDataType(item.getDataType());
                purchaseOrderDetail.setNumberOfPerBox(item.getMerchandiseNum());
                purchaseOrderDetail.setProducerId(item.getProducerId());
                purchaseOrderDetail.setMaterialProcessId(item.getProcessingId());
                purchaseOrderDetail.setWeightOfPerBox(item.getMerchandiseWeight().divide(new BigDecimal(item.getMerchandiseNum()), 2, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP));
                list.add(purchaseOrderDetail);


                GoodsBox goodsBox = new GoodsBox();
                goodsBox.setBoxCode(purchaseOrderDetail.getBoxCode());
                goodsBox.setGoodsBoxSpecId(item.getContainerId());
                boxCodeList.add(goodsBox);
            }
        }
        purchaseOrder.setList(list);

        log.error("purchaseOrder:{}", JSON.toJSONString(purchaseOrder));

        DeliveryOrder deliveryOrder = new DeliveryOrder();
        List<WarehousingEntry> entryList = new ArrayList<>();

        generateDeliver(purchaseOrder, deliveryOrder, entryList);

        sendMsg(deliveryOrder, entryList, boxCodeList, warehouse, purchaseOrder);
    }

    /**
     * 生成的仓库数据推送到仓库
     *
     * @param deliveryOrder
     * @param entryList
     * @param boxCodeList
     * @param warehouse
     * @param purchaseOrder
     * @return void
     * @author yw
     * @date 2023-08-17 10:25:40
     */
    @Override
    public void sendMsg(DeliveryOrder deliveryOrder, List<WarehousingEntry> entryList, List<GoodsBox> boxCodeList, Warehouse warehouse, PurchaseOrder purchaseOrder) {
        String topic = warehouseService.selectRegionAreaTopic(warehouse);
        ParamInfo<PurchaseOrder> paramInfo = new ParamInfo<>();
        paramInfo.setData(purchaseOrder);
        String tag = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_WAREHOUSE_PURCHASE_ENTRY;
        try {
            log.error("采购单:{}", JSON.toJSONString(paramInfo));
            producerUtil.sendAsyncMsg(topic, tag, JSON.toJSONString(paramInfo).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
        } catch (Exception e) {
            log.error("采购单信息发送异常:{}", e);
            throw new UtilException("信息发送异常");
        }
        ParamInfo<DeliveryOrder> paramInfoDelivery = new ParamInfo<>();
        paramInfoDelivery.setData(deliveryOrder);
        String tagDelivery = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_WAREHOUSE_DELIVERY_ENTRY;
        try {
            log.error("取货单:{}", JSON.toJSONString(paramInfoDelivery));
            producerUtil.sendAsyncMsg(topic, tagDelivery, JSON.toJSONString(paramInfoDelivery).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
        } catch (Exception e) {
            log.error("取货单信息发送异常:{}", e);
            throw new UtilException("信息发送异常");
        }

        ParamInfo<WarehousingEntry> paramInfoEntry = new ParamInfo<>();
        paramInfoEntry.setList(entryList);
        String tagEntry = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_WAREHOUSE_ENTRY;
        try {
            log.error("入库单{}", JSON.toJSONString(paramInfoEntry));
            producerUtil.sendAsyncMsg(topic, tagEntry, JSON.toJSONString(paramInfoEntry).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
        } catch (Exception e) {
            log.error("入库单信息发送异常:{}", e);
            throw new UtilException("信息发送异常");
        }
        if (!boxCodeList.isEmpty()) {
            goodsBoxService.syncToWms(boxCodeList, purchaseOrder.getWarehouseCode(), topic);
        }
    }

    /**
     * 提前生成仓库入库配送单/提货单，若是调整，懒得单个仓库调整，放到数据转发中心
     *
     * @param purchaseOrderInfo
     * @return void
     * @author yw
     * @date 2023-06-20 19:44:15
     */
    @Override
    public void generateDeliver(PurchaseOrder purchaseOrderInfo, DeliveryOrder deliveryOrder, List<WarehousingEntry> entryList) {
        List<DeliveryOrderDetail> deliveryOrderDetails = new ArrayList<>();
        String warehouseCode = purchaseOrderInfo.getWarehouseCode();
        List<PurchaseOrderDetail> list = purchaseOrderInfo.getList();

        deliveryOrder.setDeliveryOrderCode(purchaseOrderInfo.getDeliveryCode());
        deliveryOrder.setWarehouseCode(warehouseCode);
        deliveryOrder.setServiceType(purchaseOrderInfo.getServiceType());
        deliveryOrder.setServiceCode(purchaseOrderInfo.getServiceCode());
        deliveryOrder.setPurchaserId(purchaseOrderInfo.getCreateBy());
        deliveryOrder.setSupplierId(purchaseOrderInfo.getSupplierCode());
        deliveryOrder.setSourceId(purchaseOrderInfo.getSourceId());
        deliveryOrder.setBatchCode(purchaseOrderInfo.getPurchaseOrderCode());
        deliveryOrder.setStatus("0");
        deliveryOrder.setType("0");

        if (purchaseOrderInfo.getConfirmStatus().equals("3")) {
            deliveryOrder.setStatus("3");
        }

        for (PurchaseOrderDetail detail : list) {
            DeliveryOrderDetail deliveryOrderDetail = new DeliveryOrderDetail();
            deliveryOrderDetail.setDeliveryOrderCode(deliveryOrder.getDeliveryOrderCode());
            deliveryOrderDetail.setWarehouseCode(warehouseCode);
            deliveryOrderDetail.setPurchaseOrderCode(detail.getPurchaseOrderCode());
            deliveryOrderDetail.setSupplierCode(detail.getSupplierCode());
            deliveryOrderDetail.setNumber(detail.getPurchaseQuantity());
            deliveryOrderDetail.setStatus("0");
            deliveryOrderDetail.setSourceId(detail.getSourceId());
            deliveryOrderDetail.setBoxCode(detail.getBoxCode());
            deliveryOrderDetail.setDeliveryTime(LocalDateTime.now());
            //箱为单位
            deliveryOrderDetail.setDeliveryNumber(1);
            if (purchaseOrderInfo.getConfirmStatus().equals("3")) {
                deliveryOrderDetail.setStatus("3");
            }
            deliveryOrderDetails.add(deliveryOrderDetail);

            generateEntry(detail, purchaseOrderInfo, entryList);
        }
        log.error("generateDeliver入库单：{}", JSON.toJSONString(entryList));
        deliveryOrder.setList(deliveryOrderDetails);
    }

    /**
     * 入库单据提前生成，不写在仓库，若是调整，懒得单个仓库调整，放到数据转发中心
     *
     * @param detail
     * @param purchaseOrderInfo
     * @return void
     * @author yw
     * @date 2023-06-20 20:26:43
     */
    public void generateEntry(PurchaseOrderDetail detail, PurchaseOrder purchaseOrderInfo, List<WarehousingEntry> entryList) {
        WarehousingEntry warehousingEntry = new WarehousingEntry();
//        warehousingEntry.setEntryCode("RKD" + IdUtil.getSnowflake().nextIdStr());
        warehousingEntry.setEntryCode(purchaseOrderInfo.getPurchaseOrderCode());
        warehousingEntry.setServiceCode(purchaseOrderInfo.getServiceCode());
        warehousingEntry.setWarehouseCode(purchaseOrderInfo.getWarehouseCode());
        warehousingEntry.setDataType(detail.getDataType());
        warehousingEntry.setBoxCode(detail.getBoxCode());
        warehousingEntry.setSourceId(detail.getSourceId());
//        warehousingEntry.setServiceCode(purchaseOrderInfo.getServiceCode());
        warehousingEntry.setServiceType(purchaseOrderInfo.getServiceType());
        warehousingEntry.setOrderType(purchaseOrderInfo.getDeliveryType());
        warehousingEntry.setSpuId(detail.getSpuId());
        warehousingEntry.setSpecCode(detail.getSpecCode());
        warehousingEntry.setSkuCode(detail.getSkuCode());
        warehousingEntry.setWarrantyDate(detail.getWarrantyDate());
        warehousingEntry.setPrice(BigDecimal.ZERO);
        warehousingEntry.setQuantity(detail.getPurchaseQuantity());
        warehousingEntry.setWeight(detail.getWeight());
        warehousingEntry.setPurchaserId("");
        warehousingEntry.setUnit(detail.getUnit());
        warehousingEntry.setSupplierCode(detail.getSupplierCode());
        warehousingEntry.setProducerId(detail.getProducerId());
        if (detail.getProduceDate() != null && detail.getWarrantyDate() != null) {
            warehousingEntry.setShelfLife(detail.getProduceDate().plusDays(detail.getWarrantyDate()));
        }
        warehousingEntry.setPickTime(detail.getProduceDate());
        warehousingEntry.setBatchCode(detail.getBatchCode());
        warehousingEntry.setProvenance("");
        warehousingEntry.setStatus("0");
        warehousingEntry.setNumberOfPerBox(detail.getNumberOfPerBox());
        warehousingEntry.setWeightOfPerBox(detail.getWeightOfPerBox());
        entryList.add(warehousingEntry);
    }
}
